<?php
namespace App\Common\Tencent\Cos;

use Illuminate\Support\Facades\Config;
use Qcloud\Cos\Client;

class CosBucket {
    protected $SecretId = '';
    protected $SecretKey = '';
    protected $AppId = '';
    //储存桶
    protected $Bucket = '';
    //地区
    protected $Region = "ap-beijing";
    protected $Schema = "https";
    protected static $cosClient;

    public function __construct($Bucket ,$Region='',$Schema='')
    {
        $config = Config::get('TencentConfig.cos');
        $this->SecretId = $config['SecretId'];
        $this->SecretKey = $config['SecretKey'];
        $this->AppId = $config['AppId'];
        $this->Bucket = $Bucket.'-'.$this->AppId;
        if(!empty($Region)){
            $this->Region = $Region;
        }
        if(!empty($Schema)){
            $this->Schema = $Schema;
        }
    }

    /**
     * 初始话
     */
    private function init(){
        $cosConfig = [
            'region' => $this->Region,
            'schema' => $this->Schema, //协议头部，默认为http
            'credentials'=>[
                'secretId'  =>  $this->SecretId,
                'secretKey' => $this->SecretKey,
            ]
        ];
        self::$cosClient = new Client($cosConfig);
    }

    //查询存储桶列表
    public function ListBuckets()
    {
        $this->init();
        try {
            //请求成功
            $result = $this::$cosClient->listBuckets();
            print_r($result);
        } catch (\Exception $e) {
            //请求失败
            return $e->getMessage();
        }
    }

    /**
     * 创建存储桶
     * @return string
     */
    public function PutBucket()
    {
        $this->init();
        try {
            $result = $this::$cosClient->createBucket(array(
                'Bucket' => $this->Bucket //格式：BucketName-APPID
            ));
            return $result;
        } catch (\Exception $e) {
            // 请求失败
            return $e->getMessage();
        }
    }

    /**
     * 检索存储桶及其权限
     * @return string
     */
    public function HeadBucket()
    {
        try {
            $result = $this::$cosClient->headBucket(array(
                'Bucket' => $this->Bucket //格式：BucketName-APPID
            ));
            // 请求成功
            return $result;
        } catch (\Exception $e) {
            // 请求失败
            return $e->getMessage();
        }
    }

    /**
     * 删除存储桶
     * @return string
     */
    public function DelBucket()
    {
        $this->init();
        try {
            $result = $this::$cosClient->deleteBucket(array(
                'Bucket' => $this->Bucket //格式：BucketName-APPID
            ));
            // 请求成功
            return $result;
        } catch (\Exception $e) {
            // 请求失败
            return $e->getMessage();
        }
    }

}
